package com.example.supermarket_back.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.supermarket_back.service.LoginService;
import com.example.supermarket_back.utils.CommonUtil;
import com.example.supermarket_back.utils.constants.ErrorEnum;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/login")
public class Login {



    @Resource
    private LoginService loginService;

    //账号登陆
    @PostMapping("/verifyAccount")
    public JSONObject loginAccount(@RequestBody  JSONObject json) {
        String username = json.containsKey("username") ? json.getString("username") : null;
        String password = json.containsKey("password") ? json.getString("password") : null;
        if (username==null||password==null) {
            return CommonUtil.errorJson(ErrorEnum.E_407);
        }else {
            return loginService.verifyUserAccount(username,password);
        }
    }

    //邮箱登陆
    @PostMapping("/verifyEmail")
    public JSONObject loginEmail(@RequestBody  JSONObject json) {
        String email = json.containsKey("email") ? json.getString("email") : null;
        String password = json.containsKey("password") ? json.getString("password") : null;
        if (email==null||password==null) {
            return CommonUtil.errorJson(ErrorEnum.E_407);
        }else {
            return loginService.verifyUserEmail(email,password);
        }
    }

    //登出
    @PostMapping("/updatePassWord")
    public JSONObject updatePassWord(@RequestBody  JSONObject json) {
        String email = json.containsKey("email") ? json.getString("email") : null;
        String password = json.containsKey("password") ? json.getString("password") : null;
        String captcha = json.containsKey("captcha") ? json.getString("captcha") : null;
        if (email==null||password==null||captcha==null) {
            return CommonUtil.errorJson(ErrorEnum.E_407);
        }else {
            return loginService.updatePassWord(email,password,captcha);
        }
    }

    //登出
    @GetMapping("/loginOut")
    public JSONObject loginOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        boolean flag=loginService.loginOut(token);
        return flag?CommonUtil.successJson():CommonUtil.errorJson(ErrorEnum.E_400);
    }
}
